package cn.org.alan.exam.service.impl;

import cn.org.alan.exam.common.exception.ServiceRuntimeException;
import cn.org.alan.exam.mapper.JobMapper;
import cn.org.alan.exam.mapper.UserJobDetailsMapper;
import cn.org.alan.exam.model.entity.Job;
import cn.org.alan.exam.model.entity.User;
import cn.org.alan.exam.model.entity.UserJobDetails;
import cn.org.alan.exam.model.vo.job.StudentJobPageVo;
import cn.org.alan.exam.model.vo.job.UserJobDetailsVo;
import cn.org.alan.exam.service.IUserJobDetailsService;
import cn.org.alan.exam.utils.SecurityUtil;
import com.aliyun.oss.ServiceException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 说明：
 *
 * @Author Alan
 * @Version 1.0
 * @Date 2025/4/3 10:09 PM
 */
@Service
public class UserJobDetailsServiceImpl implements IUserJobDetailsService {
    @Autowired
    private UserJobDetailsMapper userJobDetailsMapper;
    @Autowired
    private JobMapper jobMapper;

    @Override
    public UserJobDetails add(UserJobDetails userJobDetails) {
        Integer userId = SecurityUtil.getUserId();
        LambdaQueryWrapper<UserJobDetails> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserJobDetails::getJobId,userJobDetails.getJobId())
                .eq(UserJobDetails::getUserId,userId);
        List<UserJobDetails> userJobDetails1 = userJobDetailsMapper.selectList(queryWrapper);
        if(!userJobDetails1.isEmpty()){
            throw new ServiceRuntimeException("已经作答，无法再次作答");
        }
        userJobDetails.setUserId(userId);
        userJobDetails.setScore(0.0);
        userJobDetails.setState(0);
        int insert = userJobDetailsMapper.insert(userJobDetails);
        if (insert > 0) {
            return userJobDetails;
        }
        throw new ServiceRuntimeException("新增作业回答失败");
    }

    @Override
    public Page getStudentJobPage(Integer pageNum, Integer pageSize, String title) {
        Page<StudentJobPageVo> page = new Page<>(pageNum,pageSize);
        Integer gradeId = SecurityUtil.getGradeId();
        Integer userId = SecurityUtil.getUserId();
        return jobMapper.getStudentJobPage(page,gradeId,title,userId);
    }

}
